package com.darthsith.droidathome.mobile;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainScreen extends Activity implements OnClickListener {

	private Button button;
	private EditText url;
	private EditText command;
	private TextView result;
	private HttpClient httpClient;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        url=(EditText)findViewById(R.id.url);
        result=(TextView)findViewById(R.id.result);
        command=(EditText)findViewById(R.id.command);
        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(this);
    }

	@Override
	public void onClick(View v) {
		if (v.getId()==button.getId()) {
			httpClient=new DefaultHttpClient();
			String uri="http://"+url.getText()+":8080/droid-at-home-0.1"+command.getText();
			Log.i("URL", uri);
			HttpGet request=new HttpGet(uri);
	        try {
				HttpResponse response=httpClient.execute(request);
				String str=EntityUtils.toString(response.getEntity());
				result.setText(str);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater=new MenuInflater(this);
		menuInflater.inflate(R.menu.menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId()==R.id.insertUser) {
			Intent intent=new Intent(this, AddUserActivity.class);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}
}